#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
媒体服务
提供媒体文件访问服务
"""

import os
from pathlib import Path
from typing import List, Dict, Any

from app.core.config import settings


class MediaServer:
    """媒体服务"""
    
    def __init__(self):
        self.recording_path = os.path.abspath(settings.RECORDING_PATH)
        self.screenshot_path = os.path.abspath(settings.SCREENSHOT_PATH)
        
        # 确保目录存在
        Path(self.recording_path).mkdir(parents=True, exist_ok=True)
        Path(self.screenshot_path).mkdir(parents=True, exist_ok=True)
        
    def list_recordings(self) -> List[Dict[str, Any]]:
        """列出录制文件"""
        recordings = []
        
        if not os.path.exists(self.recording_path):
            return recordings
            
        for item in os.listdir(self.recording_path):
            item_path = os.path.join(self.recording_path, item)
            if os.path.isdir(item_path):
                m3u8_path = os.path.join(item_path, "index.m3u8")
                if os.path.exists(m3u8_path):
                    stat = os.stat(item_path)
                    recordings.append({
                        "name": item,
                        "path": f"/view/hls/{item}/index.m3u8",
                        "size": stat.st_size,
                        "mtime": stat.st_mtime
                    })
                    
        return recordings
        
    def get_screenshots(self) -> List[Dict[str, Any]]:
        """获取截图列表"""
        screenshots = []
        
        if not os.path.exists(self.screenshot_path):
            return screenshots
            
        for item in os.listdir(self.screenshot_path):
            if item.lower().endswith(('.jpg', '.jpeg', '.png')):
                item_path = os.path.join(self.screenshot_path, item)
                stat = os.stat(item_path)
                screenshots.append({
                    "name": item,
                    "path": f"/screenshots/{item}",
                    "size": stat.st_size,
                    "mtime": stat.st_mtime
                })
                
        return screenshots
        
    def get_hls_url(self, record_dir: str) -> str:
        """获取HLS播放地址"""
        return f"/view/hls/{record_dir}/index.m3u8"
        
    def get_recording_path(self, record_dir: str) -> str:
        """获取录制目录路径"""
        return os.path.join(self.recording_path, record_dir)


# MediaServer单例实例
_media_server_instance = None

def get_media_server():
    """获取MediaServer单例实例"""
    global _media_server_instance
    if _media_server_instance is None:
        _media_server_instance = MediaServer()
    return _media_server_instance